//
//  HomeClassifyCell.m
//  SleepingElf
//
//  Created by karong on 2023/10/10.
//

#import "HomeClassifyCell.h"
#import "GRHorizontalFlowLayout.h"
#import "HomeClassifyItemCell.h"
#import "HomeModel.h"

@interface HomeClassifyCell ()
@property (weak, nonatomic) IBOutlet UICollectionView *listView;
@property (strong, nonatomic) NSArray *dataArray;
@property (nonatomic, assign) NSInteger selectIndex;
@end

@implementation HomeClassifyCell
- (void)awakeFromNib {
    [super awakeFromNib];
    self.selectIndex = 0;
}

- (void)setDataWithObject:(NSArray *)object {
    self.dataArray = object;
    [self.listView reloadData];
}

#pragma mark - UICollectionViewDelete

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    HomeClassifyItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HomeClassifyItemCell" forIndexPath:indexPath];
    [cell setDataWithObject:self.dataArray[indexPath.row] select:self.selectIndex == indexPath.row];
    return cell;
}


#pragma mark - UICollectionViewDelegateFlowLayout

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(0, 13, 0, 13);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 15;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    HomeClassify * homeClassify = self.dataArray[indexPath.row];
    CGFloat width = [homeClassify.name boundingRectWithSize:CGSizeMake(MAXFLOAT, 0.0) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:14 weight:(UIFontWeightMedium)]} context:nil].size.width;
    return CGSizeMake(width + 18, 22);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if ([self.delegate respondsToSelector:@selector(homeClassifyCellDidSelectItem:)]) {
        [self.delegate homeClassifyCellDidSelectItem:self.dataArray[indexPath.row]];
    }
    self.selectIndex = indexPath.row;
    [self.listView reloadData];
}
@end
